package net.towee.model.account.impl;

import java.util.ArrayList;
import java.util.List;

import net.towee.model.account.AccountPermission;
import net.towee.model.account.Role;
import net.towee.server.persistence.impl.MongoDbStore;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.PostLoad;

/**
 * Role container
 * @author c58
 */
@Entity(MongoDbStore.ACCOUNT_ROLES_COLLECTION)
public class RoleImpl implements Role {
	@Id private String id;
	private List<AccountPermission> permissions;
	private String name;
	private boolean owner;
	
	public RoleImpl(){}
	public RoleImpl(String id, String name){
		this(id, name, false);
	}
	public RoleImpl(String id, String name, boolean owner){
		this.id = id;
		this.name = name;
		this.permissions = new ArrayList<AccountPermission>();
		this.owner = owner;
	}
	
	@PostLoad
	private void createEmptyArrays(){
		if(permissions == null)
			permissions = new ArrayList<AccountPermission>();
	}
	
	@Override
	public String getId() {
		return id;
	}
	
	@Override
	public String getName() {
		return name;
	}

	@Override
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public boolean hasPermissions(AccountPermission... perm) {
		if(owner)
			return true;
		
		for(AccountPermission p : perm) {
			if(!permissions.contains(p))
				return false;
		}
		
		return true;
	}

	@Override
	public void addPermission(AccountPermission perm) {
		if(!permissions.contains(perm))
			permissions.add(perm);
	}

	@Override
	public void removePremission(AccountPermission perm) {
		permissions.remove(perm);
	}

	@Override
	public boolean equals(Object o) {
		if(o == this)
			return true;
		if(o instanceof Role && ((Role)o).getId().equals(getId()))
			return true;
		
		return false;
	}
	@Override
	public boolean isOwner() {
		return owner;
	}
	@Override
	public void setId(String string) {
		this.id = string;
	}
}
